var getInfoUrl = '../ajax/ajax_get_info.php';
var searchUrl = '../ajax/ajax_search.php';
var feedbackUrl = '../ajax/ajax_feedback.php';
var _epsilon_neg;     // Negative SGA score
var _epsilon_pos;     // Positive SGA score
var _pvalue_neg;         // Negative P-value
var _pvalue_pos;         // Positive P-value
var _rvalue;        // significant or notsignificant
var bypass_array = [];
var vis;
var _lastFilter;
var edge_checked = {};
var network_json;
var cw_options = {
    swfPath: "../inc/swf/CytoscapeWeb",
    flashInstallerPath: "../inc/swf/playerProductInstall",
    flashAlternateContent: '<div class="ui-state-error ui-corner-all"><p>This content requires the Adobe Flash Player.</p><p><a href="http://get.adobe.com/flashplayer/"><img width="160" height="41" border="0" alt="Get Adobe Flash Player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg"></a></p></div>'
};

var _condition_type = {
    1: 'FG26',
    2: 'FG30',
    3: 'TS26',
    4: 'TS30'
};

//Mapping network groups to node colors:
var nodeColorMapper = {
    attrName: "ngc",                            // nodeGroupCode
    entries: [
        {attrValue: "q",value: "#FF9086"},      // Query nodes
        {attrValue: "r",value: "#ffffff"}       // Result nodes
    ]
};

//Mapping network groups to edge colors:
var edgeColorMapper = {
    attrName: "egc",                                // edgeGroupCode
    entries: [
        {attrValue: "c",value: "#c3844c"},         //Correlation
        {attrValue: "ai",value: "#2fb56d"},         //Interaction
        {attrValue: "pai", value: "green"},	    //Positive Interaction
        {attrValue: "nai", value: "red"},	    //Negative Interaction
        {attrValue: "coexp",value: "#FBD10A"},      //Co-expression
        {attrValue: "coloc",value: "#6261fc"},      //Co-localization
        {attrValue: "pi",value: "#9EB5E6"},         //Physical interactions
        {attrValue: "spd",value: "#00CCFF"},        //Shared protein domains
    ]
};

var cw_style = {
    nodes : {
        shape: "ELIPSE",
        color: {
            defaultValue: "#999999",
            discreteMapper: nodeColorMapper
        },
        opacity: 1,
        size : {
            defaultValue: 24, 
            continuousMapper : {
                attrName: "count", 
                minValue: 24, 
                maxValue: 48
            }
        },
        borderColor: "#808080",
        borderWidth: 1,
        label: {
            passthroughMapper: {
                attrName: "id"
            }
        },
        labelFontWeight: "bold",
        labelGlowColor: "#ffffff",
        labelGlowOpacity: 1,
        labelGlowBlur: 3,
        labelGlowStrength: 20,
        labelHorizontalAnchor: "center",
        labelVerticalAnchor: "bottom",
        selectionBorderColor: "#000000",
        selectionBorderWidth: 2,
        selectionGlowColor: "#ffff33",
        selectionGlowOpacity: 0.6,
        hoverBorderColor: "#000000",
        hoverBorderWidth: 2,
        hoverGlowColor: "#aae6ff",
        hoverGlowOpacity: 0.8
    },
    edges : {
        color: {
            defaultValue: "#999999",
            discreteMapper: edgeColorMapper
        },
        width : {
            continuousMapper : {
                attrName : "distance", 
                minValue : 1, 
                maxValue: 4
            }
        }
    }
};

$(function(){
    $('#sidebar1').css({
        'overflow': 'auto'
    });
    
    $('input.marksolved').live('click', function(e){
        var id = e.target.id;
        $.ajax({
            type: 'POST',
            url: feedbackUrl,
            dataType: "JSON",
            data: {
                id: id,
                feedback_type:'update'
            },
            async: false,
            success: function(data){
                showFeedback();
            }
        });
    });
    
    /**
     * Submit users' commnet
     */
    $('#feedback #feedback_submit').live('click', function(e){
        var comment = $('#feedback #feedback_comment').val();
        if (comment == null || comment.length == 0){
            alert('Please put in your feedback.');
            $('#feedback #feedback_comment').focus();
            return;
        }
        
        var name = $('#feedback #feedback_name').val();
        if (name == null || name.length == 0){
            alert('Please put in your name.');
            $('#feedback #feedback_name').focus();
            return;
        }
        comment = comment.replace(/[\r\n]/gi, "<br/>");
        $.ajax({
            type: 'POST',
            url: feedbackUrl,
            dataType: "JSON",
            data: {
                feedback_comment:comment, 
                feedback_name:name,
                feedback_type:'set'
            },
            async: false,
            success: function(){
                $('#feedback #feedback_comment').val("");
                $('#feedback #feedback_name').val("");
                var color = $('#feedback #feedback_table tr:eq(1)').attr('bgcolor') == "#CCCCFF" ? "#FFFFFF" : "#CCCCFF";
                var html= "<tr class='feedback_detail' bgcolor=" + color + "><td style='word-wrap:break-word;width: 500px;' textalign='left'>" + comment + "</td><td width='150px' textalign='center'>" + name + "</td><td width='100px' textalign='center'>No</td></tr>";
                $('#feedback #feedback_table tbody').prepend(html);
            }
        });
    });
    
    /**
     * Action when clicking the node of tree view.
     */
    $('.sidebar1 #queryresult .treenode').live('click', function(e){
        var selected = false;
        // Create an random color to distinguish different gene.
        var randomColor = getRandomColor();
        // the random color shouldn't be the same of background color.
        while (randomColor == 'white'){
            randomColor = getRandomColor();
        }

        // When the node of tree is selected, cancle selection.
        if($(e.target).hasClass('selected')){
            $(e.target).removeClass('selected');
            $(e.target).css({
                'background': 'white'
            });
            selected = false;
        } else {
            $(e.target).addClass('selected');
            $(e.target).css({
                'background': randomColor
            });
            selected = true;
        }
        if($('#result_container div.active table').length != 0){
            highlightline($(e.target).attr('id'), selected, randomColor);
        } else {
            highlightnode($(e.target).attr('id'), selected, randomColor);
        }
    });
    
    $('#nodescolor').live('click', function(e){
        var style = vis.visualStyle();
        if($(e.target).hasClass('pressed')){
            $(e.target).removeClass('pressed');
            style.nodes.color = '#fffefe';
        } else {
            $(e.target).addClass('pressed');
            style.nodes.color = 'green';
        }
        vis.visualStyle(style);
    });
    
    $('#edgescolor').live('click', function(e){
        var style = vis.visualStyle();
        if($(e.target).hasClass('pressed')){
            style.edges.color = '#999999';
            $(e.target).removeClass('pressed');
        } else {
            $(e.target).addClass('pressed');
            style.edges.color = 'yellow';
        }
        vis.visualStyle(style);
    });
    
    $('.quick_launch_node').live('click', function(e){
        var total_height = $('#result_container div.active table').height();
        var quick_launch_height = $('#result_container .active .quick_launch').height();
        var node_height = $(e.target).offset().top - $('#result_container .active .quick_launch').offset().top;
        // The node in the quick launch bar has a border which is 1px, so the height is (node_height - 1)
        var table_node_height = (node_height - 1) * total_height / quick_launch_height - $(window).height() / 2;
        // var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
        var $body = $('#tabs-center .content');
        
        $body.animate({
            scrollTop: table_node_height
        }, 400)
        
        // $('#tabs-center .content').scrollTop(table_node_height);
    });
    
    /**
     * Popup the infomation dialog of gene.
     */
    $('#result_container div.active table a').live('click', function(e){
    	var type = 't';
    	var group = 'table';
    	var id = e.target.id;
    	$.ajax({
            type: 'POST',
            url: getInfoUrl,
            dataType: 'JSON',
            data: {
                viewType: type
                , group: group
                , id: id
                , score_neg: _epsilon_neg
                , score_pos: _epsilon_pos
                , p_neg: _pvalue_neg
                , p_pos: _pvalue_pos
                , rvalue: _rvalue
            },
            async: true,
            success: function(data){
            	var htmlInfo = makeTargetInfoHtml(type, group, data);
            	var title = "Description of " + id;
            	var diaId = "dia-" + id;
                var leftPos = $(e.target).closest('b').offset().left + $(e.target).closest('b').width();
                var topPos = ($(e.target).closest('b').offset().top + 220 > $(window).height()) ? $(e.target).closest('b').offset().top - 220 : $(e.target).closest('b').offset().top;
            	$(e.target).closest('b').dialog({
                    id: diaId,
                    title: title,
                    width: 400,
                    height: 220,
                    left: leftPos,
                    top: topPos,
                    cancelBtn: false,
                    iconTitle:false,
                    rang: true,
                    html:htmlInfo
                });
            	$(e.target).closest('b').trigger("click");
            }
        });
    });
    
    /**
     * Operations when resizing the brower's window.
     */
    $(window).resize(function() {
        
        if($('#result_container .active .quick_launch').length != 0){
            var new_height = $(window).height();
            var new_left = $(window).width();
            $('#result_container .active .quick_launch').css({
                'height': (new_height - 200) + 'px',
                'left':(new_left - 23) + 'px'
            });
            var total_height = $('#result_container div.active table').height();
            var quick_launch_height = $('#result_container .active .quick_launch').height();
            var count = $('#result_container .active .quick_launch .quick_launch_node').length;
            for (var i = 0; i < count; i++){
                var ql_id = $('#result_container .active .quick_launch .quick_launch_node:eq(' + i + ')').attr('id');
                var id = ql_id.split('_')[0] + '_' + ql_id.split('_')[1] + '_' + ql_id.split('_')[2];
                var node_height = $('#result_container div.active table tr.trnode[id="' + id + '"]').offset().top - $('#result_container div.active table tr.trnode[id="' + id + '"]').parent().offset().top + 104;
                var ql_new_height = (node_height * quick_launch_height) / total_height;
                $('#result_container .active .quick_launch .quick_launch_node:eq(' + i + ')').css({
                    'top': ql_new_height + 'px'
                });
            }
        }
    });
})
/**
 * Create a random color for the selected node.
 */

function getRandomColor(){
    var arrHex = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
    var strHex = "#";
    var index;
    for (var i = 0; i < 6; i++){
        index = Math.round(Math.random() * 15);
        strHex += arrHex[index];
    }
    return strHex;
}
function move(){
    var height=$(document).scroll();
    if(height>65){
        $(".sidebar1").animate({
            "marginTop":height+"px"
        });
    }else{
        $(".sidebar1").animate({
            "marginTop":"0px"
        });
    }
}

function highlightline(id, selected, randomColor){
    if (selected){
        $('#result_container div.active table tr.trnode[id*="' + id + '"]').css({
            'background': randomColor
        });
        var count = $('#result_container div.active table tr.trnode[id*="' + id + '"]').length;
        var total_height = $('#result_container div.active table').height();
        var quick_launch_height = $('#result_container .active .quick_launch').height();
        for (var i = 0; i < count; i++){
            var node_height = $('#result_container div.active table tr.trnode[id*="' + id + '"]:eq(' + i + ')').offset().top - $('#result_container div.active table tr.trnode[id*="' + id + '"]:eq(' + i + ')').parent().offset().top + 104;
            var location_in_ql_height = (node_height * quick_launch_height) / total_height;
            var node_id = $('#result_container div.active table tr.trnode[id*="' + id + '"]:eq(' + i + ')').attr('id') + '_ql';
            $('#result_container .active .quick_launch').find('.new').removeClass('new');
            var location_html = '<hr id="' + node_id + '" class="quick_launch_node new" size="3" color="'+ randomColor + '" />';
            $('#result_container .active .quick_launch').append(location_html);
            $('#result_container .active .quick_launch .new').css({
                'top': (location_in_ql_height) + 'px'
            });
        }
    } else {
        $('#result_container div.active table tr.trnode[id*="' + id + '"][id$="0"]').css({
            'background': '#CCCCFF'
        });
        $('#result_container div.active table tr.trnode[id*="' + id + '"][id$="1"]').css({
            'background': '#FFFFFF'
        });
        $('#result_container .active .quick_launch .quick_launch_node[id*=' + id + ']').remove();
    }
}

function highlightnode(id, active, randomColor){
    var selectedTreeNode = $('#sidebar1 div.active li a.selected');
    var count = selectedTreeNode.length;
    var bypass = {
        nodes: { }, 
        edges: { }
    };
    for (var i = 0; i < count; i++){
        var nodeId = $('#sidebar1 div.active li a.selected:eq('+ i + ')').attr('id');
        var nodeColor = $('#sidebar1 div.active li a.selected:eq('+ i + ')').css('background-color');
        var props = {
            color: nodeColor
        };
        bypass["nodes"][nodeId] = props;
    }
    vis.visualStyleBypass(bypass);
    var active_id = $('#result_container .active').attr('id');
    if (active_id.split('_')[2] == 'i'){
        bypass_array[0] = bypass;
    } else {
        bypass_array[1] = bypass;
    }
    
}

function loadTreeView(id, data){
    $("#" + id).jstree({
        "themes" : {
            "theme" : "default",
            "dots" : false,
            "icons" : false
        },
        "json_data" : {
            "data": data,
            "progressive_render" : true
        },
        "plugins" : [ "themes", "json_data"]
    });
}

function showResultView(query_names, epsilon_neg, pvalue_neg, epsilon_pos, pvalue_pos, rvalue, view, type, query_type){
    _epsilon_neg = epsilon_neg;
    _epsilon_pos = epsilon_pos;
    _pvalue_neg = pvalue_neg;
    _pvalue_pos = pvalue_pos;
    _rvalue = rvalue;
    
    if (view == 'nv' && type == 'i'){
        $('#sidebar1 #choosebox').show();
    } else {
        $('#sidebar1 #choosebox').hide();
    }
    $('#feedback').hide();
    $('#result_container').show();
    var activeId = 'result_' + view + '_' + type;
    var treeId = 'tree_' + view + '_' + type;
    $('#result_container').find('.active').hide();
    $('#sidebar1').find('.active').hide();
    $('#result_container').find('.active').removeClass('active');
    $('#sidebar1').find('.active').removeClass('active');
    if ($('#' + activeId).length != 0){
        $('#' + activeId).addClass('active');
        $('#' + treeId).addClass('active');
        $('#' + activeId).show();
        $('#' + treeId).show();
        return;
    }
    if($('#sidebar1 userquery').length != 0){
        var marginTopSize = $('#sidebar1 userquery').offset().bottom + 100;
        $('#sidebar1 #loading').css({
            'marginTop': marginTopSize + 'px'
        });
    }
    $('#sidebar1 #loading').show();
    $('#result_container #loading').show();
    var resultView = '<div class="result_view active" id="'+ activeId + '">';
    resultView += '</div>';
    $('#result_container').append(resultView);
    $('#result_container').find('.active').show();
    getResultData(query_names, epsilon_neg, pvalue_neg, epsilon_pos, pvalue_pos, rvalue, view, type, query_type);
}

function getResultData(query_names, epsilon_neg, pvalue_neg, epsilon_pos, pvalue_pos, rvalue, view, type, query_type){
    var activeId = 'result_' + view + '_' + type;
    $.ajax({
        type: 'POST',
        url: searchUrl,
        dataType: "JSON",
        data: {
            query_names:query_names, 
            epsilon_neg:epsilon_neg, 
            pvalue_neg:pvalue_neg, 
            epsilon_pos:epsilon_pos, 
            pvalue_pos:pvalue_pos, 
            rvalue:rvalue,
            view:view, 
            type:type,
            query_type:query_type
        },
        async: false,
        success: function(data){
            $('#sidebar1 #loading').hide();
            if ($('#sidebar1 #userquery').length == 0){
                var userquery = '<div class="treeview" id="userquery"></div>';
                $('#sidebar1').prepend(userquery);
                loadTreeView("userquery", eval('(' + data.tree_query_data + ')'));
            }
            var treeId = 'tree_' + view + '_' + type;
            var queryresult = '<div class="treeview active" id="' + treeId +  '"></div>';
            $('#sidebar1').append(queryresult);
            loadTreeView(treeId, eval('(' + data.tree_result_data + ')'));
            
            switch(view){
                case 'tv':{
                    var title = (type == 'n' ? ('Negative Interaction(' + data.table_list_count + ')') : (type == 'p' ? ('Positive Interaction(' + data.table_list_count + ')') : ('Correlation(' + data.table_list_count + ')')));
                    var tableHtml = '<div class="div_detail" id="div_detail"><h1 align="center">' + title + '</h1>';
                    if (data.table_list_count > 0){
                        tableHtml += '<table class="table_detail" id="table_detail" border=0 bgcolor="white" cellSpacing=3 cellpadding=5 width=100%>';
                        if (type == 'n' || type == 'p'){
                            tableHtml += '<tr bgcolor="#9999FF"><th align="center">Query gene</th><th align="center">Query Strain</th><th align="center">Array gene</th><th align="center">Array Strain</th><th>SGA score</th><th nowrap>p-value</th><th>Condition</th></tr>';
                            $.each(eval('(' + data.table_list_data + ')'),function(i,e){
                                var stream = makeInteractionItemNode(i,e);
                                tableHtml += stream;
                            });
                        } else {
                            tableHtml += '<tr bgcolor="#9999FF"><th align="center">Gene1</th><th align="center">Gene2</th><th>Correlation</th>';
                            $.each(eval('(' + data.table_list_data + ')'),function(i,e){
                                var stream = makeCorrelationItermNode(i,e);
                                tableHtml += stream;
                            });
                        }
                        tableHtml += '</table>';
                    }
                    tableHtml += '</div><div class="quick_launch"></div>';
                    var screenHeight = $(window).height();
                    var screenWidth = $(window).width();
                    $('#result_container #loading').hide();
                    $('#' + activeId).append(tableHtml);
                    $('#' + activeId + ' .quick_launch').css({
                        'height': (screenHeight - 200) + 'px',
                        'left': (screenWidth - 23) + 'px'
                    });
                }
                break;
                case 'nv':{
                    if (type == 'i'){
                        var chooseHtml = '<div class="choosebox" id="choosebox">'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="pai" checked disabled>Positive Interaction<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:green;"></div>'+
                                '</div>'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="nai" checked disabled>Negative Interaction<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:red;"></div>'+
                                '</div>'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="coexp" checked onclick="showEdge(this)">Co-expression<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:#FBD10A;"></div>'+
                                '</div>'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="coloc" checked onclick="showEdge(this)">Co-localization<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:#6261fc;"></div>'+
                                '</div>'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="pi" checked onclick="showEdge(this)">Physical interactions<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:#9EB5E6;"></div>'+
                                '</div>'+
                                '<div class="chooseitem">'+
                                '<input class="choosetype" type="checkbox" name="reltype" value ="spd" checked onclick="showEdge(this)">Shared protein domains<br>'+
                                '<div class="choosecolor" style="width: 100px;height:5px;margin-left:20px;background-color:#00CCFF;"></div>'+
                                '</div></div>';
                            $('#tabs-west li#tab-network-selector').show();
                        $('#tab-panel-west-2 .ui-tabs-panel').prepend(chooseHtml);
                        
                    }
                    var cwId = 'cw_' + view + '_' + type;
                    var cwHtml = '<div class="tools">'+
                    '<select name="layout" id="layout" onchange="layout(this)">' + 
                    '<option value="1">ForceDirected</option>' + 
                    '<option value="2">Circle</option>' + 
                    '<option value="3">Radial</option>' + 
                    '<option value="4">Tree</option>' + 
                    '</select>' + 
                    '</div>' + 
                    '<div class="cw_view" id="' + cwId + '">Cytoscape Web will replace the contents of this div with your graph.</div>';
                    $('#result_container #loading').hide();
                    $('#' + activeId).append(cwHtml);
                    makeCytoscapeWebView(cwId, eval('(' + data.cw_node_data + ')'), eval('(' + data.cw_edge_data + ')'));
                }
                break;
                default:
                    break;
            }
        }
    });
}

/**
 * Make up a node of interaction result table.
 */
function makeInteractionItemNode(i,e){
    var id = e.g1Feature + '_' + e.g2Feature + '_' + (i % 2 == 0 ? 0 : 1);
    var item = '<tr id="' + id + '" class="trnode" bgcolor="' + (i % 2 == 0 ? '#CCCCFF' : '#FFFFFF') + '">' + 
    '<td style="width: 250px;"><b><a id="' + e.g1Feature + '" href="javascript:void(0)">' + e.g1Feature + '</a></b> - <b>' + (e.g1Name == '' ? e.g1Feature : e.g1Name) + '</b>' + (e.g1Alias == '' ? '<br/>' : '(' + e.g1Alias + ')<br/>') + '</td>' + 
    '<td style="width: 50px;text-align:center">' + e.s1Strain.split('_')[1] + '</td>' + 
    '<td style="width: 250px;"><b><a id="' + e.g2Feature + '" href="javascript:void(0)">' + e.g2Feature + '</a></b> - <b>' + (e.g2Name == '' ? e.g2Feature : e.g2Name) + '</b>' + (e.g2Alias == '' ? '<br/>' : '(' + e.g2Alias + ')<br/>') + '</td>' +
    '<td style="width: 50px;text-align:center">' + e.s2Strain.split('_')[1] + '</td>' + 
    '<td style="text-align: left;">' + e.score + '</td><td style="text-align: left;">' + e.pValue + '</td><td style="text-align:center;">' + _condition_type[e.condition] + '</td></tr>';
    return item;
}

/**
 * Make up a node of correlation result table.
 */
function makeCorrelationItermNode(i, e){
    var id = e.g1Feature + '_' + e.g2Feature + '_' + (i % 2 == 0 ? 0 : 1);
    var item = '<tr id="' + id + '" class="trnode" bgcolor="' + (i % 2 == 0 ? '#CCCCFF' : '#FFFFFF') + '">' + 
    '<td style="width: 300px;"><b><a href="http://db.yeastgenome.org/cgi-bin/search/quickSearch?query=' + e.g1Feature +  '" target="_blank">' + e.g1Feature + '</a></b> - <b>' + (e.g1Name == '' ? e.g1Feature : e.g1Name) + '</b>' + (e.g1Alias == '' ? '<br/>' : '(' + e.g1Alias + ')<br/>') + '</td>' + 
    '<td style="width: 300px;"><b><a href="http://db.yeastgenome.org/cgi-bin/search/quickSearch?query=' + e.g2Feature +  '" target="_blank">' + e.g2Feature + '</a></b> - <b>' + (e.g2Name == '' ? e.g2Feature : e.g2Name) + '</b>' + (e.g2Alias == '' ? '<br/>' : '(' + e.g2Alias + ')<br/>') + '</td>' +
    '<td style="text-align: left;">' + e.score + '</td></tr>';
    return item;
}

/**
 * Make up the result of Cytoscape Web View.
 */
function makeCytoscapeWebView(id, nodes_data, edges_data){
    network_json = {
        dataSchema : 
        {
            nodes : [{
                name : "count", 
                type : "number"
            },{
                name: "ngc",
                type: "string"
            }],
            edges : [{
                name : "distance", 
                type : "number"
            },{
                name: "pvalue",
                type: "number"
            },{
                name: "egc",
                type: "string"
            }]
        },
        data : 
        {
            nodes : nodes_data,
            edges : edges_data
        }
    };
    vis = new org.cytoscapeweb.Visualization(id, cw_options);
    vis.ready(function(){
        vis = this;
        var active_id = $('#result_container .active').attr('id');
        if(bypass_array[0] != null && active_id.split('_')[2] == 'i'){
            vis.visualStyleBypass(bypass_array[0]);
        } else if (bypass_array[1] != null && active_id.split('_')[2] == 'c'){
            vis.visualStyleBypass(bypass_array[1]);
        }
        
        if (!vis.hasListener('click', 'nodes')){
            vis.addListener('click', 'nodes', function(event){
                handle_click(event);
            });
        }
        if (!vis.hasListener('click', 'edges')){
            vis.addListener('click', 'edges', function(event){
                handle_click(event);
            });
        }
        
        if (active_id.split('_')[2] == 'i'){
            if (_lastFilter != null){
                vis.filter("edges", _lastFilter, true);
            } else {
                edge_checked['pai'] = true;
                edge_checked['nai'] = true;
                edge_checked['coexp'] = true;
                edge_checked['coloc'] = true;
                edge_checked['pi'] = true;
                edge_checked['spd'] = true;
            }
        }        
    });
    vis.draw({
        network: network_json,
        visualStyle : cw_style,
        panZoomControlVisible: true,
        edgesMerged: false,
        nodeLabelsVisible: true,
        edgeLabelsVisible: false,
        nodeTooltipsEnabled: false,
        edgeTooltipsEnabled: false,
        layout : {
            name : "ForceDirected",
            options : {
                weightAttr : "distance"
            }
        }
    });
}

function makeTargetInfoHtml(type, group, data){
    var html = '';
    if (group == 'nodes'){
        html += '<span class="node_name">Primary SGDID: </span><span class="node_value">'+ data.primary_sgdid + '</span></br>' + 
        '<span class="node_name">Feature Name: </span><span class="node_value"><a target="_blank" href="http://www.yeastgenome.org/cgi-bin/locus.fpl?locus=' + data.feature_name + '">' +data.feature_name + '</a></span></br>' + 
        (data.standard_gene_name == '' ? '' : '<span class="node_name">Standard Gene Name: </span><span class="node_value">'+data.standard_gene_name + '</span></br>') +  
        (data.alias == '' ? '' : '<span class="node_name">Alias: </span><span class="node_value">'+data.alias + '</span></br>') + 
        (data.parent_feature_name == '' ? '' : '<span class="node_name">Parent Feature Name: </span><span class="node_value">'+data.parent_feature_name + '</span></br>') + 
        (data.secondary_sgdid == '' ? '' : '<span class="node_name">Secondary SGDID: </span><span class="node_value">'+data.secondary_sgdid + '</span></br>') + 
        (data.chromosome == '' ? '' : '<span class="node_name">Chromosome: </span><span class="node_value">'+data.chromosome + '</span></br>') + 
        (data.start_coordinate == '' ? '' : '<span class="node_name">Start Coordinate: </span><span class="node_value">'+data.start_coordinate + '</span></br>') + 
        (data.stop_coordinate == '' ? '' : '<span class="node_name">Stop Coordinate: </span><span class="node_value">'+data.stop_coordinate + '</span>');
        
    } else if (group == 'edges') {
        if (type == 'c'){
            html += '<ul class="network_list tooltip"><li class="network_group"><div class="label"><div class="per_cent_text"><span>Correlation Score</span></div><div class="network_name">Gene 1 | Gene 2</div></div>';
            $.each(eval(data),function(i,e){
                html += '<ul style="display: block;"><li class="network"><div class="label"><div class="per_cent_text"><span>' + e.weight + '</span></div><div class="network_name">' + e.gene1 + ' | ' + e.gene2 + '</div></div></li></ul>';
            });
        } else if (type == 'pai' || type == 'nai'){
            html += '<ul class="network_list tooltip"><li class="network_group"><div class="label"><div class="per_cent_text"><span>SGA Score | P-Value | Condition</span></div><div class="network_name">Query | Array</div></div>';
            $.each(eval(data),function(i,e){
                html += '<ul style="display: block;"><li class="network"><div class="label"><div class="per_cent_text"><span>' + e.weight + ' | ' + e.pvalue + ' | ' + _condition_type[e.condition] + '</span></div><div class="network_name">' + e.gene1 + '_' + e.s1name + ' | ' + e.gene2 + '_' + e.s2name + '</div></div></li></ul>';
            });
            html += '</li></ul>';
        } else {
            html += '<ul class="network_list tooltip"><li class="network_group"><div class="label"><div class="per_cent_text"><span>Network Name | Weight</span></div><div class="network_name">Gene 1 | Gene 2</div></div>';
            $.each(eval(data),function(i,e){
                html += '<ul style="display: block;"><li class="network"><div class="label"><div class="per_cent_text"><span><a target="_blank" href="http://www.ncbi.nlm.nih.gov/pubmed?term=' + e.pubmed + '">' + e.network + '</a> | ' + e.weight + '</span></div><div class="network_name">' + e.gene1 + ' | ' + e.gene2 + '</div></div></li></ul>';
            });
            html += '</li></ul>';
        }
    } else if (group == 'table'){
    	html += '<span class="node_name">Gene Description: </span><br /><span class="node_value">'+ data.description + '</span><br /><br />' + 
    			'<a href="http://db.yeastgenome.org/cgi-bin/search/quickSearch?query=' + data.feature_name +  '" target="_blank">More...</a>';
    } else {}
    return html;
}

function showTargetInfo(x, y, id, group, type, data){
    var showId = id.split('_')[0] + '-' + id.split('_')[1];
    var left = $('#result_container').offset().left + x + (x > 300 ? -310 : 10);
    var height = $('#result_container').offset().top + y;
    var top = height + 260 > $(window).height() ? height - 160 : height + 40;
    var htmlInfo = makeTargetInfoHtml(type, group, data);
    $('.clicked_target').dialog({
        id: id,
        title: showId,
        width: 500,
        height: 220,
        left: left,
        top: top,
        cancelBtn: false,
        iconTitle:false,
        rang: true,
        html:htmlInfo
    });
    $('.clicked_target').trigger("click");
}

function handle_click(event) {
    var viewType = event.target.data.id.split('_')[2];
    var group = event.group;
    var target = event.target;
    var id = target.data.id;
    
    // Click event
    if (event.type == 'click'){
        if (group != 'nodes' && group != 'edges'){
            return;
        } else {
            $.ajax({
                type: 'POST',
                url: getInfoUrl,
                dataType: 'JSON',
                data: {
                    viewType: viewType
                    , group: group
                    , id: id
                    , score_neg: _epsilon_neg
                    , score_pos: _epsilon_pos
                    , p_neg: _pvalue_neg
                    , p_pos: _pvalue_pos
                    , rvalue: _rvalue
                },
                async: true,
                success: function(data){
                    if ($('.clicked_target').length != 0){
                        $('.clicked_target').remove();
                    }
                    var divHtml = '<div class="clicked_target" id=' + id + ' style="position: relative;z-index: 12; top:' + (target.y - 600) +'px; left:'+ target.x + 'px; width: 2px;height: 2px;"></div>';
                    $('#result_container').append(divHtml);
                    showTargetInfo(event.mouseX, event.mouseY, id, group, viewType, data);
                }
            });
        }
    }
}

function layout(layout){
    var selectedValue = layout.selectedIndex;
    var layoutType = layout.options[selectedValue].text;
    var vis_network = vis.networkModel();
    var vis_visualStyle = vis.visualStyle();
    vis.draw({
        network: vis_network,
        visualStyle : vis_visualStyle,
        layout : {
            name : layoutType,
            options : {
                weightAttr : "distance"
            }
        }
    });
}

function clear() {
    document.getElementById("info").innerHTML = "";
}
    
function print(msg) {
    document.getElementById("info").innerHTML += "<p>" + msg + "</p>";
}

function formatNum(num,decimals){
    if(isNaN(num)||isNaN(decimals)){
        return(0);
    }else{
        num=num.toString();
        decimals=parseInt(decimals);
        if(num.indexOf('.')==-1){
            return(num);
        }else{
            var b=num.substring(0,num.indexOf('.')+decimals+1);
            var c=num.substring(num.indexOf('.')+decimals+1,num.indexOf('.')+decimals+2);
            if(c==""){
                return(b);
            }else{
                if(parseInt(c)<5){
                    return(b);
                }else{
                    return((Math.round(parseFloat(b)*Math.pow(10,decimals))+Math.round(parseFloat(Math.pow(0.1,decimals).toString().substring(0,Math.pow(0.1,decimals).toString().indexOf('.')+decimals+1))*Math.pow(10,decimals)))/Math.pow(10,decimals));
                }
            }
        }
    }
}

function showEdge(eve){
    
    //alert(eve.value);
    var total_type = 5;
    $('#choosebox input').each(function() {
        var type = $(this).attr('value');
        var checked = true;
        if ($(this).attr("checked") === undefined){
            total_type--;
            checked = false;
        }
        edge_checked[type] = checked;
    });
    
    if (total_type == 5){
        vis.removeFilter("edges", true);
        _lastFilter = null;
    }else {
        _lastFilter = function(edge) {
            return edge_checked[edge.data.egc];
        };
        vis.filter("edges", _lastFilter, true);
    }
}

function showFeedback(){
    if ($('#feedback #feedback_table tbody').find('tr').length != 0){
        $('#feedback #feedback_table tbody').find('tr').remove();
    }
    $.ajax({
        type: 'POST',
        url: feedbackUrl,
        dataType: "JSON",
        data: {
            feedback_type:'get'
        },
        async: false,
        success: function(data){
            var html = '';
            $.each(eval(data.feedbacks),function(i,e){
                var color = i % 2 == 0 ? "#FFFFFF" : "#CCCCFF";
                html += "<tr class='feedback_detail' bgcolor='" + color + "'><td textalign='left'>" + e.comment + "</td><td textalign='center'>" + e.author + "</td><td textalign='center'>"+ (e.solved == 0 ? "<input class='marksolved' id='" + e.id + "' type='button' value='Mark As Solved'>" : "Solved") + "</td></tr>";
            });
            $('#feedback #feedback_table tbody').append(html);
        }
    });
}
